<template>
  <div id="detail">
    <detail-nav-bar class="detail-nav" ref="nav" @titleClick="titleClick" />
    <scroll
      class="contents"
      ref="scroll"
      :probe-type="3"
      @scroll="contentScroll"
    >
      <!-- 属性：要用驼峰不然大写字母会被html识别出小写的  （事件就可以） -->
      <detail-swiper :top-images="topImages" />
      <detail-base-info :goods="goods" />
      <detail-shop-info :shop="shop" />
      <detail-goods-info
        :detail-info="detailInfo"
        @imageLoad="imageLoad"
      ></detail-goods-info>
      <!-- 参数 -->
      <detail-param-info
        ref="params"
        :param-info="paramInfo"
      ></detail-param-info>
      <!-- 评论 -->
      <detail-comment-info
        ref="comment"
        :comment-info="commentInfo"
      ></detail-comment-info>
      <!-- 推荐 -->
      <goods-list ref="recommend" :goods="recommends" />
    </scroll>
    <!-- 底部工具栏 -->
    <detail-bottom-bar
      @addCart="addToCart"
      @kefu="kefu"
      @dianpu="dianpu"
      @shoucang="shoucang"
      @goumai="goumai"
    ></detail-bottom-bar>
    <!-- 回到顶部 -->
    <back-top @click.native="backClick" v-show="isShowBackTop"></back-top>

    <!-- 添加到购物车弹窗 -->
    <!-- <toast :message="message" :isShow="show"></toast> -->
  </div>
</template>

<script>
import DetailNavBar from "./childComps/DetailNavBar";
import DetailSwiper from "./childComps/DetailSwiper";
import DetailBaseInfo from "./childComps/DetailBaseInfo";
import DetailShopInfo from "./childComps/DetailShopInfo";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo";
import DetailParamInfo from "./childComps/DetailParamInfo";
import DetailCommentInfo from "./childComps/DetailCommentInfo";
import DetailBottomBar from "./childComps/DetailBottomBar";

import Scroll from "components/common/scroll/Scroll";
// 首页goodslist组件复用
import GoodsList from "components/content/goods/GoodsList";
// import BackTop from "components/content/backTop/BackTop";
// import Toast from "components/common/toast/Toast";

import { debounce } from "common/utils";
import { itemListenerMixin, backTopMixin } from "common/mixin";

import { mapActions } from "vuex";

import {
  getDetail,
  getRecomment,
  Goods,
  Shop,
  GoodsParam,
} from "network/detail";

export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    Scroll,
    GoodsList,
    DetailBottomBar,
    // BackTop,
    // Toast,
  },
  // 混入
  mixins: [itemListenerMixin, backTopMixin],
  data() {
    return {
      iid: null,
      // 顶部轮播图片
      topImages: [],
      // 商品信息
      goods: {},
      // 店铺信息
      shop: {},
      // 详情信息
      detailInfo: {},
      // 参数属性
      paramInfo: {},
      // 评论信息
      commentInfo: {},
      // 推荐信息
      recommends: [],
      // 主题的y值
      themeTopYs: [],
      // 用于获取主题的y值的防抖操作函数
      getThemeTopY: null,
      currentIndex: 0,
      // isShowBackTop: false,
    };
  },
  created() {
    // 1.获取商品的id
    this.iid = this.$route.params.iid;

    // 2.根据iid请求详情数据
    getDetail(this.iid).then((res) => {
      const data = res.result;
      // 1.获取顶部的图片轮播数据
      this.topImages = res.result.itemInfo.topImages;

      // 2.获取商品信息   detail.js里Goods构造函数的对象
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );

      // 3.创建店铺信息的对象
      this.shop = new Shop(data.shopInfo);

      // 4.保存商品的详情数据
      this.detailInfo = data.detailInfo;

      // 5.获取参数的信息
      this.paramInfo = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );

      // 6.取出评论信息
      if (data.rate.cRate != 0) {
        this.commentInfo = data.rate.list[0];
      }

      // 等前面的东西渲染完了，再来回调这个函数，才能保证都拿到了值
      /* this.$nextTick(() => {
        // 根据最新的数据，对应的DOM是已经被渲染出来了
        // 但是图片依然是没有加载完(目前获取到offsetTop不包含其中的图片)
        this.themeTopYs.push(0);
        // 组件不能直接拿offsetTop 要加$el
        this.themeTopYs.push(this.$refs.params.$el.offsetTop);
        this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
        this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        console.log(this.themeTopYs);
      }); */
    });

    // 3.请求推荐数据
    getRecomment().then((res) => {
      this.recommends = res.data.list;
    });

    // 4.给getThemeTopY赋值(对给this.themeTopYs赋值的操作进行防抖)
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = [];
      this.themeTopYs.push(0);
      // 组件不能直接拿offsetTop 要加$el
      this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      // 在后面再加一个最大值 方便后面的for循环判断
      // Number.MAX_VALUE js的最大值
      this.themeTopYs.push(Number.MAX_VALUE);
    }, 100);
  },
  mounted() {},
  destroyed() {
    this.$bus.$off("itemImageLoad", this.itemImgListener);
  },
  methods: {
    // 映射actions.js里的addCart函数
    ...mapActions(["addCart"]),
    imageLoad() {
      // refresh在mixin.js里面已经创建好了
      this.refresh();
      // this.$refs.scroll.refresh();
      this.getThemeTopY();
    },
    titleClick(index) {
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 800);
    },
    // 监听滚动
    contentScroll(position) {
      // 1.获取y值
      const positionY = -position.y;

      let length = this.themeTopYs.length;
      // 2.positonY和主题中的值进行对比
      for (let i = 0; i < length - 1; i++) {
        // for (let i in this.themeTopYs)
        // i 是 str 如果i=0  i+1=01

        // 条件一：防止赋值的过程过于频繁
        if (
          this.currentIndex !== i &&
          positionY >= this.themeTopYs[i] &&
          positionY < this.themeTopYs[i + 1]
        ) {
          this.currentIndex = i;
          this.$refs.nav.currentindex = this.currentIndex;
        }
      }

      // 3.是否显示回到顶部
      this.isShowBackTop = -position.y > 1000;
    },

    // 添加到购物车
    addToCart() {
      // 1.获取购物车需要展示的信息
      const product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;

      // 2.将商品添加到购物车
      // 通过 Vuex 到 store/index.js 中 action.js里面的addCart
      // this.$store.commit("addCart", product);
      this.addCart(product).then((res) => {
        // res 就是 actions.js里resolve()的东西

        // 弹窗显示添加成功
        this.$toast.show(res, 1500);
      });
      /* this.$store.dispatch("addCart", product).then((res) => {
        console.log(res);
      }); */
    },

    // 有待开发
    kefu() {
      this.$toast.show("抱歉噢亲，客服功能还未开发哟！！", 1500);
    },
    dianpu() {
      this.$toast.show("抱歉噢亲，店铺功能还未开发哟！！", 1500);
    },
    shoucang() {
      this.$toast.show("抱歉噢亲，收藏功能还未开发哟！！", 1500);
    },
    goumai() {
      this.$toast.show("购买失败，请先加入购物车噢亲！！", 1500);
    },

    /* backClick() {
      this.$refs.scroll.scrollTo(0, 0, 800);
    }, */
  },
};
</script>

<style scoped>
#detail {
  /* 盖住下面的tabbar */
  position: relative;
  z-index: 1;
  background-color: #fff;
  height: 100vh;
}

.detail-nav {
  position: relative;
  z-index: 1;
  background-color: #fff;
}

.contents {
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
  overflow: hidden;
}
</style>